<template>
  <div class="user__wrapper">
    <div class="user__top">
      <el-form :inline="true" :model="user" ref="userForm">
        <el-form-item label="用户ID" prop="userId">
          <el-input placeholder="用户ID" v-model="user.userId"></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input placeholder="用户名称" v-model="user.userName"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="user.state">
            <el-option :value="0" label="所有"></el-option>
            <el-option :value="1" label="在职"></el-option>
            <el-option :value="2" label="离职"></el-option>
            <el-option :value="3" label="实习"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="userQuery">查询</el-button>
          <el-button type="primary" @click="resetForm('userForm')"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <div class="user__bottom">
      <div class="active">
        <el-button type="primary" v-has:add="'user-add'" @click="handeDion"
          >创建用户</el-button
        >
        <el-button
          type="danger"
          v-has:delete="'user-delete'"
          @click="handelDeletion"
          >批量删除</el-button
        >
      </div>
      <el-table
        :data="userList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" />
        <el-table-column
          v-for="item in tabCloum"
          :key="item.role"
          :prop="item.prop"
          :label="item.label"
          :formatter="item.formatter"
          align="center"
        >
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              size="mini"
              @click="handeEdit(scope.row)"
              v-has:edit="'user-edit'"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              v-has:del="'user-del'"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pages">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="page.total"
          :page-size="page.pageSize"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
    <!-- 表格结束 -->
    <!-- 新增用户 -->
    <el-dialog title="新增用户" v-model="showDialog" width="500px">
      <el-form
        ref="addUserFrom"
        :model="addUser"
        :rules="addUserRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input
            type="text"
            placeholder="请输入用户名"
            v-model="addUser.userName"
            :disabled="action == 'edit'"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input
            placeholder="请输入用户邮箱"
            :disabled="action == 'edit'"
            v-model="addUser.userEmail"
          >
            <template #append>@qq.com</template>
          </el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input placeholder="请输入手机号" v-model="addUser.mobile" />
        </el-form-item>
        <el-form-item label="岗位" prop="job">
          <el-input placeholder="请输入岗位" v-model="addUser.job" />
        </el-form-item>
        <el-form-item label="QQ号" prop="imgUrl" required>
          <el-input
            placeholder="必须填,用来获取头像"
            v-model="addUser.imgUrl"
          />
        </el-form-item>
        <el-form-item label="称呼" prop="call">
          <el-input placeholder="伙伴云登记的名称" v-model="addUser.call" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="addUser.state">
            <el-option value="1" label="在职" />
            <el-option value="2" label="离职" />
            <el-option value="3" label="试用期" />
          </el-select>
        </el-form-item>
        <el-form-item label="系统角色">
          <el-select
            placeholder="请选择系统角色"
            v-model="addUser.roleList"
            multiple
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in roleList"
              :key="item._id"
              :label="item.roleName"
              :value="item._id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门管理" prop="dentId">
          <el-cascader
            v-model="addUser.deptId"
            :options="deptList"
            :props="{
              checkStrictly: true,
              value: '_id',
              label: 'deptName',
            }"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handeClos">取 消</el-button>
          <el-button type="primary" @click="handeSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- /新增用户结束 -->
  </div>
</template>

<script>
import { toRaw } from '@vue/reactivity'
import util from '@/utils/utils.js'
export default {
  name: 'User',
  data () {
    return {
      // 初始化用户表单对象
      user: {
        userId: '',
        userName: '',
        state: 1
      },
      // 添加用户表单数据
      addUser: {
        state: "3",
      },
      // 分页参数
      page: {
        pageNum: 1,
        pageSize: 10,
      },
      // 批量删除参数
      deleteList: [],
      // 显示弹窗
      showDialog: false,
      // 表格渲染参数
      tabCloum: [
        {
          label: "用户ID",
          prop: "userId"
        },
        {
          label: "用户名称",
          prop: "userName"
        },
        {
          label: "用户邮箱",
          prop: "userEmail"
        },
        {
          label: "用户角色",
          prop: "role",
          formatter (row, cloum, value) {
            return {
              0: "管理员",
              1: "普通用户"
            }[value]
          }
        },
        {
          label: "用户状态",
          prop: "state",
          formatter (row, cloum, value) {
            return {
              1: "在职",
              2: "离职",
              3: "试用期"
            }[value]
          }
        },
        {
          label: "注册时间",
          prop: "createTime",
          formatter (row, cloum, value) {
            return util.formateDate(new Date(value))
          }
        },
        {
          label: "最后登录时间",
          prop: "lastLoginTime",
          formatter (row, cloum, value) {
            return util.formateDate(new Date(value))
          }
        },
      ],
      // 用户列表
      userList: [],
      // 创建用户验证规则
      addUserRules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: 'blur' },
          { min: 3, max: 15, message: "长度必须3-10", trigger: 'blur' }
        ],
        userEmail: [
          { required: true, message: "请输入邮箱", trigger: 'blur' },
        ],
        mobile: [
          { pattern: /1[3-9]\d{9}/, message: '请输入合法手机号', trigger: 'blur' }
        ],
      },
      // 权限列表
      roleList: [],
      // 部门列表
      deptList: [],
      // 定义用户操作行为
      action: 'add'
    }
  },
  methods: {
    /**
     * @type 表单重置
     */
    resetForm (form) {
      this.$refs[form].resetFields();
    },
    /**
     * @type 条件查询
     */
    userQuery () {
      this.getUserList()
    },
    /**
     * @type 获取用户列表
     */
    async getUserList () {
      const params = { ...this.user, ...this.page }
      try {
        const { list, page } = await this.$api.getUserList(params)
        this.userList = list
        this.page.total = page.total
      } catch (error) {

      }
    },
    /**
     * @type 分页点击事件
     */
    handleCurrentChange (curren) {
      this.page.pageNum = curren
      this.getUserList()
    },
    /**
     * @type 删除单个用户
     */
    async handleDelete (row) {
      const params = {
        userId: [row.userId]
      }
      try {
        const res = await this.$api.deleteUser(params)
        if (res) {
          this.$message.success('删除成功')
          this.getUserList()
        } else {
          this.$message.error('删除失败')
        }
      } catch (e) {
        this.$message.error(e.msg)
      }
    },
    /**
     * @type 批量删除
     */
    async handelDeletion () {
      if (this.deleteList.length < 0) {
        this.$message.error('请选择要删除的用户')
        return;
      }
      const params = {
        userId: this.deleteList
      }
      try {
        const res = await this.$api.deleteUser(params)
        if (res.nModified == this.deleteList.length) {
          this.$message.success(`删除成功:${res.nModified}条`)
          this.getUserList()
        } else {
          this.$message.error(`删除失败:${this.deleteList.length - res.nModified}条`)
          this.getUserList()
        }
      } catch (e) {
        throw error(e.msg)
      }
    },
    /**
     * @type 表格多选
     */
    handleSelectionChange (val) {
      let arr = []
      val.map(item => {
        arr.push(item.userId)
      })
      this.deleteList = arr
    },
    /**
     * @type 创建用户按钮
     */
    handeDion () {
      this.action = 'add'
      this.showDialog = true
    },
    /**
     * @type 获取角色列表
     */
    async getAllRoleList () {
      const res = await this.$api.getAllRoleList()
      this.roleList = res
    },
    /**
     * @type 获取部门
     */
    async getDeptList () {
      const res = await this.$api.getDeptList()
      this.deptList = res
    },
    /**
     * @type 弹窗取消
     */
    handeClos () {
      this.resetForm('addUserFrom')
      this.showDialog = false
    },
    /**
     * @type 表单提交
     */
    handeSubmit () {
      this.$refs.addUserFrom.validate(async (valid) => {
        if (valid) {
          let params = toRaw(this.addUser)
          params.userEmail += '@qq.com'
          params.action = this.action
          try {
            const result = await this.$api.userSubmit(params)
            this.$message.success("用户创建成功")
            this.handeClos()
            this.getUserList()
          } catch (error) {
            this.$message.error(`未知异常${error}`)
          }
        } else {
          this.$message.error('验证错误,请输入符合信息')
        }
      })

    },
    /**
     * @type 编辑
     */
    handeEdit (row) {
      this.action = 'edit'
      this.showDialog = true
      // 页面渲染完后执行方法
      this.$nextTick(() => {
        // 将row数据克隆给表单
        Object.assign(this.addUser, row)
      })
    }
  },
  mounted () {
    this.getUserList()
    this.getAllRoleList()
    this.getDeptList()
  }
}
</script>

<style lang="scss" scoped>
.user__wrapper {
  background: #fff;
}
.user__top {
  height: 0.8rem;
  padding: 0.24rem;
  border-bottom: 0.01rem solid #ebeef1;
}
.user__bottom {
  background: #ebeef1;
  padding-top: 0.3rem;
  .active {
    background: #fff;
    padding: 0.27rem;
  }
  .pages {
    text-align: right;
    padding: 0.1rem 0.27rem;
    background: #fff;
  }
}
</style>